package com.propertree.mailer.config;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.propertree.mailer.bean.EmailAttributes;
import com.propertree.mailer.bean.EmailAttributesConfiguration;

public class EmailAttributeHelper {

	public static EmailAttributes createEmailAttribute(EmailAttributesConfiguration config) {
		EmailAttributes emailAttribues = new EmailAttributes();
		emailAttribues.setSubject(readFile(config.getEmailSubjectFile()));
		emailAttribues.setBody(readFile(config.getEmailBodyFile()));
		//emailAttribues.setAttachments(getAttachments(config.getEmailAttachmentFile()));
		return emailAttribues;
	}

	private static String readFile(String filePath) {
		FileReader fis = null;
		BufferedReader br = null;
		String text = "";
		try {
			fis = new FileReader(filePath);
			br = new BufferedReader(fis);

			String sCurrentLine;
			while ((sCurrentLine = br.readLine()) != null) {
				text += sCurrentLine;
			}
			return text;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return text;

	}

	public static Map<String, String> getAttachments(String attachmentFileName) {
		String filePath = ClassLoader.getSystemResource(attachmentFileName).getPath();
		// "D:/Hitesh/CodeBase/trunk/run/02-Feb-2013/Unibera/attachmentsFileName.txt";//
		Map<String, String> fileAttachmentMap = new HashMap<String, String>();
		FileReader fis = null;
		BufferedReader br = null;
		try {
			fis = new FileReader(filePath);
			br = new BufferedReader(fis);
			String attachmentName;
			while ((attachmentName = br.readLine()) != null) {
				String attachmentFilePath = ClassLoader.getSystemResource(attachmentName).getPath();
				fileAttachmentMap.put(attachmentName, attachmentFilePath);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileAttachmentMap;
	}
}
